<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Auth;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use Reponse;
use View;
use App\Utils;
use App\Tag;
use App\Task;
use App\TasksTags;


class TagController extends Controller
{
	const KEYS = ["name", "description", "externallink"];

	public function index()
	{
		return $this->getView();
	}

	public function create(Request $request) {
		$tag = Tag::create($request->only(self::KEYS));
		$tasks = $request->except(array_merge(self::KEYS, ["_token"]));
		foreach ($tasks as $taskId => $name) {
			TasksTags::create(array(
				"tagid" => $tag->id,
				"taskid" => $taskId,
			));
		}
		return $this->getView();
	}
	
	public function update(Request $request, $id) {
		$tag = Tag::find($id);
		$tag->update($request->only(self::KEYS));
		$tasks = $request->except(array_merge(self::KEYS, ["_token"]));
		TasksTags::where('tagid', $tag->id)->delete();
		foreach ($tasks as $taskId => $name) {
			TasksTags::create(array(
				"tagid" => $tag->id,
				"taskid" => $taskId,
			));
		}
		return $this->getView();
	}
	
	public function delete($id) {
		$tag = Tag::find($id);
		$tag->delete();
		TasksTags::where('tagid', $tag->id)->delete();
		return $this->getView();
	}

	/**
	 * @return mixed
	 */
	public function getView()
	{
		$tags = Tag::where('delete', '0')->get();
		$tasks_tags = TasksTags::all();
		$tasks = Task::all();
		$covered_tasks = array();
		foreach ($tags as $index => $tag) {
			$id = $tag->id;
			$tag_task_names = array();
			$tag_task_ids = array();
			foreach ($tasks_tags as $tt) {
				if ($tt->tagid === $id) {
					array_push($tag_task_ids, $tt->taskid);
					$covered_tasks[$tt->taskid] = 1;
					foreach ($tasks as $index => $task) {
						if ($tt->taskid === $task->id) {
							array_push($tag_task_names, $task->title);
						}
					}
				}
			}
			$tag->tasknames = join(",", $tag_task_names);
			$tag->taskids = join(",", $tag_task_ids);
		}
		return view("tags.tag")
			->with('tags', $tags)
			->with('tasks', Task::all())
			->with('covered_tasks', $covered_tasks);
	}
}
